'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 登陆相关
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var pomelo = require('pomelo');
var channelUtil = require('../../../util/channelUtil');

/**
 *
 * @param app
 * @returns {Remote}
 */
module.exports = function (app) {
    return new Remote(app);
};

var Remote = function (app) {
    this.app = app;
};

var remote = Remote.prototype;

/**
 * 踢掉玩家
 */
remote.kickUser = function (msg, cb) {
    var role_id = msg.query.role_id;
    pomelo.app.get('sessionService').kick(role_id, function () {
        cb(null);
    });
};

/**
 * 添加到联盟频道
 */
remote.addUnionChannel = function (union_id, role_id, cb) {
    var self = this;
    var globalChannelService = pomelo.app.get('globalChannelService');
    globalChannelService.add(union_id, role_id, self.app.get('serverId'), cb);
};

/**
 * 从联盟频道移除连接
 */
remote.removeUnionChannel = function (union_id, role_id, cb) {
    var self = this;
    var globalChannelService = pomelo.app.get('globalChannelService');
    globalChannelService.leave(union_id, role_id, self.app.get('serverId'), cb);
};

/**
 * 停服维护
 */
remote.stopServer = function (cb) {
    console.log('--------停服维护---------');

    var app = {
        get: function () {
            return null;
        }
    };

    // 设置停服标志
    var enterHandler = require('../handler/entryHandler.js');
    var enter_handler = enterHandler(app);
    enter_handler.lockServer(null, null, function () {
        // 踢掉所有在线玩家
        pomelo.app.get('globalChannelService').getMembersByChannelName(
            'connector',
            channelUtil.getGlobalChannelName(),
            function (err, user_id_list) {
                _kickAllUsers(user_id_list, cb);
            });
    });
};

/**
 * 踢掉所有玩家
 */
var _kickAllUsers = function (user_id_list, callback) {
    console.log('--------踢掉所有在线玩家---------');
    var sessionService = pomelo.app.get('sessionService');
    async.eachSeries(user_id_list, function (role_id, cb) {
        console.log('---踢掉玩家:', role_id);
        sessionService.kick(role_id, cb);
    }, function (err) {
        callback(err);
    });
};

/**
 * 撤销停服
 */
remote.continueServer = function (cb) {
    console.log('--------撤销停服---------');

    var app = {
        get: function () {
            return null;
        }
    };
    var enterHandler = require('../handler/entryHandler.js');
    var enter_handler = enterHandler(app);
    enter_handler.unLockServer(null, null, cb);
};
